package com.onairm.baselibrary.utils;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.onairm.baselibrary.Init;
import com.onairm.baselibrary.net.RetrofitManager;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class StatisticsNetUtils {
    public static final String TAG = StatisticsNetUtils.class.getSimpleName();
    private static final int TIMEOUT_IN_MILLIONS = 5000;
    private volatile static StatisticsNetUtils INSTANCE;

    private String url;
    private HashMap<String, String> baseMap;

    //构造方法私有
    private StatisticsNetUtils() {
    }

    //获取单例
    public static StatisticsNetUtils getInstance() {
        if (INSTANCE == null) {
            synchronized (RetrofitManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new StatisticsNetUtils();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 异步的Get请求
     */
    public void doGetAsyn(final Map<String,String> paramMap) {
        new Thread() {
            public void run() {
                try {
                    String finalUrl=getFinalUrl(url + generateBaseParam(),paramMap);
                    String result = doGet(finalUrl);
                    Log.e(TAG, ""+result);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }.start();
    }
    private String getFinalUrl(String baseUrl,Map map){

        StringBuilder builder = mapToStr(map,false);
        if(0!=builder.toString().length()){
            builder.deleteCharAt(builder.toString().length()-1);
        }
        String paramStr=builder.toString();
        return baseUrl+paramStr;
    }

    /**
     * Get请求，获得返回数据
     *
     * @param urlStr
     * @return
     * @throws Exception
     */
    private String doGet(String urlStr) {
        Log.e(TAG, "doGet:" + urlStr);
        URL url = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
            conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            Log.e(TAG, "status:"+((null != conn)?conn.getResponseCode():0));
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                baos = new ByteArrayOutputStream();
                int len = -1;
                byte[] buf = new byte[128];

                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                baos.flush();
                return baos.toString();
            } else {
                throw new RuntimeException(" responseCode is not 200 ... ");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
            }
            conn.disconnect();
        }
        return null;
    }

    private StringBuilder mapToStr(Map map,boolean addQMark){
        StringBuilder builder = new StringBuilder();

        Set<String> keySet = map.keySet();
        Iterator<String> it = keySet.iterator();
        for (int i = 0; i < keySet.size(); i++) {
            if(addQMark){
                if (i == 0) {
                    builder.append("?");
                }
            }
            String key = it.next();
            String value= (String) map.get(key);
            if(!TextUtils.isEmpty(value)){
                builder.append(key)
                        .append("=")
                        .append(map.get(key))
                        .append("&");
            }


        }
        return builder;
    }

    public String generateBaseParam() {
        StringBuilder builder = mapToStr(baseMap,true);

        builder.append("sysV")
                .append("=")
                .append(Build.VERSION.RELEASE)
                .append("&")
                .append("dI")
                .append("=")
                .append(getSysInfo());
        builder.append("&")
                .append("ch")
                .append("=")
                .append(getChannel())
                .append("&");

        return builder.toString();
    }

    private String getSysInfo() {
        // 获取OS版本
        String arch = System.getProperty("os.arch");

        StringBuilder builder = new StringBuilder();
        builder.append(Build.BOARD)// 主板
                .append(";")
                .append(Build.SERIAL)// 硬件序列号
                .append(";")
                .append(Build.MANUFACTURER)// 硬件制造商
                .append(";")
                .append(Build.MODEL)//版本
                .append(";")
                .append(arch);//cpu架构

        return builder.toString();
    }

    public void setParams(HashMap map) {
        this.baseMap = map;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    private String getChannel() {
        String channel="";
        try {
            ApplicationInfo appInfo = Init.context.getPackageManager()
                    .getApplicationInfo(Init.context.getPackageName(), PackageManager.GET_META_DATA);
            channel = appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return channel;
        }

    }
}